package cn.tmall.controller;

import cn.tmall.pojo.*;
import cn.tmall.service.*;
import com.github.pagehelper.PageHelper;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.jws.soap.SOAPBinding;
import javax.print.attribute.standard.MediaSize;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("")
public class ForeController {
    @Resource(name = "ProductServiceImpl")
    ProductService productService;
    @Resource(name = "CategoryServiceImpl")
    CategoryService categoryService;
    @Resource(name = "UserServiceImpl")
    UserService userService;
    @Resource(name = "OrderItemServiceImpl")
    OrderItemService orderItemService;
    @Resource(name = "ReviewServiceImpl")
    ReviewService reviewService;
    @Resource(name = "ProductImageServiceImpl")
    ProductImageService productImageService;
    @Resource(name = "PropertyValueServiceImpl")
    PropertyValueService propertyValueService;
    @Resource(name = "OrderServiceImpl")
    OrderService orderService;

    @RequestMapping("forehome") //登录主页
    public String home(Model model) {
        List<Category> categoryList = categoryService.list();
        productService.fill(categoryList);
        productService.fillByRow(categoryList);

        model.addAttribute("categoryList", categoryList);
        return "fore/home";
    }

    @RequestMapping("foreregister") //注册信息与数据库判断
    public String register(Model model, User user) {
        String name = user.getName();
        name = HtmlUtils.htmlEscape(name);
        user.setName(name);
        if (userService.isExist(user.getName())) {
            model.addAttribute("msg", "用户名已经被使用,不能使用");
            model.addAttribute("user", null);
            return "fore/register";
        }
        userService.add(user);
        return "redirect:registerSuccessPage";
    }

    @RequestMapping("forelogin")    //登录信息与数据库判断，顺便给session域中存入登录成功的用户信息
    public String login(Model model, @RequestParam("name") String name, String password, HttpSession session) {
        name = HtmlUtils.htmlEscape(name);
        User user = userService.get(name, password);
        if (null == user) {
            model.addAttribute("msg", "用户名或密码错误！");
            return "fore/login";
        }
        session.setAttribute("user", user);
        return "redirect:forehome";
    }

    @RequestMapping("forelogout")   //退出登录处理，除去session域中存入的信息
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:forehome";
    }

    @RequestMapping("foreproduct")  //获取指定产品的信息，跳转查看指定产品的页面，含产品信息、购买，评价等
    public String product(Model model, int pid) {
        Product product = productService.get(pid);
        productService.setSaleAndReviewNumber(product); //设置产品的销量与评价数量
        product.setProductSingleImages(productImageService.list(pid, ProductImageService.type_single));
        product.setProductDetailImages(productImageService.list(pid, ProductImageService.type_detail));
        List<Review> reviewList = reviewService.list(pid);
        List<PropertyValue> propertyValueList = propertyValueService.list(pid);

        model.addAttribute("reviewList", reviewList);
        model.addAttribute("propertyValueList", propertyValueList);
        model.addAttribute("product", product);
        return "fore/product";
    }

    @RequestMapping("forecheckLogin")   //产品页面点击加入购物车或立即购买时的ajax模态登录判断
    @ResponseBody
    public String checkLogin(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (null == user) {
            return "fail";
        }
        return "success";
    }

    @RequestMapping("foreloginAjax")    //用模态窗口进行登录的响应
    @ResponseBody
    public String loginAjax(String name, String password, HttpSession session) {
        name = HtmlUtils.htmlEscape(name);
        User user = userService.get(name, password);
        if (null == user)
            return "fail";
        session.setAttribute("user", user);
        return "success";
    }

    @RequestMapping("forecategory") //跳转显示指定分类下所有产品的页面
    public String category(Model model, int cid, String sort) {
        Category category = categoryService.get(cid);
        productService.fill(category);
        List<Product> productList = category.getProducts();
        productService.setSaleAndReviewNumber(productList); //设置产品销量与评价数

        if (null != sort) {
            switch (sort) {
                case "review":
                    productList.sort((p1, p2) -> p2.getReviewCount() - p1.getReviewCount());
                    break;
                case "date":
                    productList.sort((p1, p2) -> p2.getCreateDate().compareTo(p1.getCreateDate()));
                    break;
                case "saleCount":
                    productList.sort((p1, p2) -> p2.getSaleCount() - p1.getSaleCount());
                    break;
                case "price":
                    productList.sort((p1, p2) -> (int)(p2.getPromotePrice() - p1.getPromotePrice()));
                    break;
                case "all":
                    productList.sort((p1, p2) -> p2.getSaleCount() * p2.getReviewCount() - p1.getSaleCount() * p1.getReviewCount());
                    break;
            }
        }

        model.addAttribute("category", category);
        return "fore/category";
    }

    @RequestMapping("foresearch")   //点击搜索按键后进行的搜索结果跳转
    public String search(Model model, String keyword) {
        PageHelper.offsetPage(0, 20);   //设置只显示20条
        List<Product> productList = productService.search(keyword);
        productService.setSaleAndReviewNumber(productList);

        model.addAttribute("productList", productList);
        return "fore/searchResult";
    }

    @RequestMapping("forebuyone")  //点击立即购买的响应，若不存在就创建，若原先有就在原先num基础上增加再结算
    public String buy(HttpSession session, int pid, int num) {
        int oiid = 0;
        boolean found = false;
        User user = (User) session.getAttribute("user");
        Product product = productService.get(pid);
        List<OrderItem> orderItemList = orderItemService.listByUser(user.getId());
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getProduct().getId().intValue() == product.getId().intValue()) {
                found = true;
                oiid = orderItem.getId();
                orderItem.setNumber(orderItem.getNumber() + num);
                orderItemService.update(orderItem);
                break;
            }
        }
        if (!found) {
            OrderItem orderItem = new OrderItem();
            orderItem.setNumber(num);
            orderItem.setPid(product.getId());
            orderItem.setUid(user.getId());
            orderItemService.add(orderItem);
            oiid = orderItem.getId();
        }
        return "redirect:forebuy?oiid=" + oiid;
    }

    @RequestMapping("forebuy")  //所有点击购买后的响应，计算所有订单项金额，用于跳转到结算页面
    public String buy(Model model, HttpSession session, String[] oiid) {
        float total = 0;    //保存总价格
        List<OrderItem> orderItemList = new ArrayList<>();
        for (String id : oiid) {
            OrderItem orderItem = orderItemService.get(Integer.parseInt(id));
            orderItemList.add(orderItem);
            total += orderItem.getNumber() * orderItem.getProduct().getPromotePrice();
        }

        session.setAttribute("orderItemList", orderItemList);
        model.addAttribute("total", total);
        return "fore/buy";
    }

    @RequestMapping("foreaddCart")  //点击加入购物车按键的ajax回应逻辑
    @ResponseBody
    public String addCart(HttpSession session, int pid, int num) {
        boolean found = false;
        User user = (User) session.getAttribute("user");
        List<OrderItem> orderItemList = orderItemService.listByUser(user.getId());
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getProduct().getId().intValue() == pid) {
                found = true;
                orderItem.setNumber(orderItem.getNumber() + num);
                orderItemService.update(orderItem);
                break;
            }
        }
        if (!found) {
            OrderItem orderItem = new OrderItem();
            orderItem.setNumber(num);
            orderItem.setUid(user.getId());
            orderItem.setPid(pid);
            orderItemService.add(orderItem);
        }
        return "success";
    }

    @RequestMapping("forecart") //跳转显示我的购物车页面前的逻辑操作
    public String cart(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<OrderItem> orderItemList = orderItemService.listByUser(user.getId());

        model.addAttribute("orderItemList", orderItemList);
        return "fore/cart";
    }

    @RequestMapping("forechangeOrderItem")  //购物车页面对订单项进行增加和减少时触发ajax
    @ResponseBody
    public String changeOrderItem(HttpSession session, int pid, int num) {
        User user = (User) session.getAttribute("user");
        if (null == user)
            return "fail";
        List<OrderItem> orderItemList = orderItemService.listByUser(user.getId());
        for (OrderItem orderItem : orderItemList) {
            if (pid == orderItem.getPid()) {
                orderItem.setNumber(num);
                orderItemService.update(orderItem);
                break;
            }
        }
        return "success";
    }

    @RequestMapping("foredeleteOrderItem")  //在购物车页面点击删除订单项时，进行的ajax回应操作
    @ResponseBody
    public String deleteOrderItem(HttpSession session, int oiid) {
        User user = (User) session.getAttribute("user");
        if (null == user)
            return "fail";
        orderItemService.delete(oiid);
        return "success";
    }

    @RequestMapping("forecreateOrder")  //在结算页面，点击提交订单时，进行的创建的操作，并再跳转到支付页面
    public String createOrder(HttpSession session, Order order) {
        User user = (User) session.getAttribute("user");
        String orderCode = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + RandomUtils.nextInt(10000);
        order.setUid(user.getId());
        order.setOrderCode(orderCode);
        order.setCreateDate(new Date());
        order.setStatus(OrderService.waitPay);

        List<OrderItem> orderItemList = (List<OrderItem>) session.getAttribute("orderItemList");
        float total = orderService.add(order, orderItemList);
        return "redirect:forealipay?oid=" + order.getId() + "&total=" + total;
    }

    @RequestMapping("forepayed")    //支付完成后跳转到支付成功页面，该页面显示本次订单的一些信息
    public String payed(Model model, int oid, float total) {
        Order order = orderService.get(oid);
        order.setPayDate(new Date());
        order.setStatus(OrderService.waitDelivery);
        orderService.update(order);

        model.addAttribute("order", order);
        return "fore/payed";
    }

    @RequestMapping("foreorder")    //查看我的订单页
    public String order(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Order> orderList = orderService.list(user.getId(), OrderService.delete);
        orderItemService.fill(orderList);
        model.addAttribute("orderList", orderList);
        return "fore/order";
    }

    @RequestMapping("foreconfirmPay")   //我的订单页面点击确认收货操作，跳转确认收货页面
    public String confirmPay(Model model, int oid) {
        Order order = orderService.get(oid);
        orderItemService.fill(order);
        model.addAttribute("order", order);
        return "fore/confirmPay";
    }

    @RequestMapping("foreorderConfirmed")   //确认收货页面点击“确认收货”，正式确认，并跳转收货成功
    public String orderConfirmed(int oid) {
        Order order = orderService.get(oid);
        order.setConfirmDate(new Date());
        order.setStatus(OrderService.waitReview);
        orderService.update(order);
        return "fore/orderConfirmed";
    }

    @RequestMapping("foredeleteOrder")  //点击删除订单时的ajax响应
    @ResponseBody
    public String deleteOrder(HttpSession session, int oid) {
        User user = (User) session.getAttribute("user");
        if (null == user)
            return "fail";
        Order order = orderService.get(oid);
        order.setStatus(OrderService.delete);
        orderService.update(order);
        return "success";
    }

    @RequestMapping("forereview")   //我的订单页面点击评价跳转评价产品页面
    public String review(Model model, int oid) {
        Order order = orderService.get(oid);
        orderItemService.fill(order);
        Product product = order.getOrderItems().get(0).getProduct();
        List<Review> reviewList = reviewService.list(product.getId());

        model.addAttribute("order", order);
        model.addAttribute("product", product);
        model.addAttribute("reviewList", reviewList);
        return "fore/review";
    }

    @RequestMapping("foredoreview") //在待评价页面提交评价
    public String doreview(HttpSession session, String content, @RequestParam("oid") int oid, @RequestParam("pid") int pid) {
        Review review = new Review();
        content = HtmlUtils.htmlEscape(content);
        User user = (User) session.getAttribute("user");
        review.setContent(content);
        review.setPid(pid);
        review.setCreateDate(new Date());
        review.setUid(user.getId());
        reviewService.add(review);
        return "redirect:forereview?oid=" + oid + "&showonly=true";
    }
}
